<?php


class Blackbird_Model_Polls extends Zend_Db_Table
{
	function fetchPollBySlug($slug)
	{
		$db = $this->getAdapter();
		$sql = 'select * from bb_poll'
			. "\n	where slug = " . $db->quote($slug) . ' and isPublished <> 0'
			. "\n		and publishedAt <= CURRENT_TIMESTAMP and (expiresAt is null or expiresAt >= CURRENT_TIMESTAMP)"
			;
		$poll = $db->fetchRow($sql);
		if (false === $poll)
			return false;
		$sql = 'select * from bb_polloption'
			. "\n	where pollId = {$poll->pollId}"
			;
		$poll->options = $db->fetchAll($sql);
		return $poll;
	}

	function votePollBySlug($slug, $pollOptionId)
	{
		$pollOptionId = (int)$pollOptionId;
		if (0 == $pollOptionId)
			return true;
		$db = $this->getAdapter();
		$sql = 'select pollId from bb_poll'
			. "\n	where slug = " . $db->quote($slug) . ' and isPublished <> 0'
			. "\n		and publishedAt <= CURRENT_TIMESTAMP and (expiresAt is null or expiresAt >= CURRENT_TIMESTAMP)"
			;
		$pollId = $db->fetchOne($sql);
		if (false === $pollId)
			return false;
		$sql = 'update bb_poll set votes = votes + 1'
			. "\n	where pollId = {$pollId}"
			;
		$db->query($sql);
		$pollOptionId = (int)$pollOptionId;
		$sql = 'update bb_polloption set votes = votes + 1'
			. "\n	where pollId = {$pollId} and pollOptionId = $pollOptionId"
			;
		return $db->query($sql) !== false;
	}

	function fetchPollsSelection()
	{
		$sql = 'select p.slug, p.question'
			. "\n	from bb_poll p"
			. "\n	where p.isPublished <> 0"
			. "\n	order by p.question"
			;
		$db = $this->getAdapter();
		$polls = array();
		foreach ($db->fetchAll($sql) as $row)
			$polls[$row->slug] = $row->question;
		return $polls;
	}
}

